<template>
    <div class="retrieve-box">
        <div class="step-box">
            <!-- 步骤条区域 -->
            <div class="steps">
                <el-steps :active="active"  align-center >
                    <el-step title="填写验证码" icon="el-icon-message" ></el-step>
                    <el-step title="获取手机验证码" icon="el-icon-mobile-phone"></el-step>
                    <el-step title="设置新密码" icon="el-icon-edit" ></el-step>
                    <el-step title="设置成功" icon="el-icon-circle-check" ></el-step>
                </el-steps>
            </div>

            <div class="contents">
                <!-- 找回密码表单区域 -->
                <el-form :label-position="labelPosition" label-width="100px" ref="form" :model="formData"  :rules="rule">
                        <div v-if="active === 0">
                            <el-form-item prop="account" label="账号">
                                <el-input v-model="formData.account" placeholder="请输入账号"></el-input>
                            </el-form-item>
                            <el-form-item prop="code" style="margin-top:15px" label="验证码">
                                <el-input placeholder="请输入验证码" prefix-icon="el-icon-circle-check" v-model="formData.code" type="code" clearable style="width: 63%">
                                </el-input>
                                <div class="retrieve-code" @click="refreshCode" >
                                    <s-identify :identifyCode="identifyCode"></s-identify>
                                </div>
                            </el-form-item>
                        </div>
                        <div  v-if="active === 1">
                            <!-- 邮箱验证区域 -->
                            <span class="email_tip">手机例子：159****5678</span>
                            <el-form-item label="绑定手机" prop="email">
                                <el-input  placeholder="请输入用户绑定的手机" v-model="formData.email" prefix-icon="el-icon-s-promotion" ></el-input>
                            </el-form-item>
                            <el-form-item label="验证码" prop="emailCode">
                                <el-input  placeholder="请输入正确的手机验证码" v-model="formData.emailCode" prefix-icon="el-icon-question"  style="width: 60%;"></el-input>
                                <!-- 发送邮箱验证码 -->
                                <el-button type="warning" @click="sendCode" :disabled="msgBtnDisabled" class="send">{{sendBtnTxt}}</el-button>
                            </el-form-item>
                        </div>

                        <div  v-if="active === 2">
                            <!-- 重置密码区域 -->
                            <span class="email_tip">设置新密码</span>
                            <el-form-item label="新密码" prop="password">
                                <el-input  placeholder="请输入新密码" v-model="formData.password" prefix-icon="iconfont icon-3702mima" show-password></el-input>
                            </el-form-item>
                            <el-form-item label="确认新密码" prop="rePassword">
                                <el-input  placeholder="请输入确认新密码" v-model="formData.rePassword" prefix-icon="el-icon-s-opportunity" show-password></el-input>
                            </el-form-item>
                        </div>

                    <div v-if="active === 3" >
                        <!-- 延迟加载区域 -->
                        <el-form-item class="load"
                            v-loading="Loading"
                            element-loading-text="拼命加载中..."
                            element-loading-spinner="el-icon-loading"
                            >
                        </el-form-item>
                    </div>
                    <div v-if="active === 4">
                        <!-- 成功提示区域 -->
                        <div class="tip_success">
                            <i class="el-icon-success icon_success" ></i>
                            <p>恭喜您，您的新密码已设置成功!<br>为保证您购物安全，建议您定期更改密码以保护账户安全。</p>
                        </div>
                    </div>

                    <!-- 按钮区域 -->
                    <div class="deployBtn">
                        <el-button type="primary" class="btn_left" @click="prev" v-if="active!==0&&active<=2">上一步</el-button>
                        <el-button type="primary" class="btn_next" @click="next()" v-if="active<2">下一步</el-button>
                        <el-button type="primary" class="btn_next" @click="refind" v-if="active==2">提交修改</el-button>

                        <el-button type="success" class="btn_next" @click="goback" v-if="active==4">立即返回</el-button>
                    </div>
                </el-form>
            </div>

        </div>
    </div>
</template>

<script>
// 引入验证码组件
import SIdentify from '../../components/SIdentify'

export default {
    components: { SIdentify },

    data() {
        //验证验证码
        const validateCode = (rule, value, callback) => {
            if (this.identifyCode !== value) {
                this.refreshCode()
                callback(new Error('请输入正确的验证码'))
                } else {
                    callback()
                }
        }
        const  validatePhoneCode = (rule,value,callback)=>{
            if(this.returnCode!==value){
                console.log(value);
                console.log(this.returnCode);
                callback(new Error('验证码错误'))
            }
            else{
                callback()
            }


        }
        // 手机号码验证
        const phoneCheck = async(rule, value, callback) => {
            let reg = /^[0-9]*$/;
            if(!reg.test(value)) {
                this.changeFlag = 2;
                return callback(new Error('请检查格式是否正确！'));
            } else {
                callback()
                }
        }
        // 密码验证
        const pwdCheck = async(rule, value, callback) => {
            let reg = /^[A-Za-z0-9]+$/;
            if(!reg.test(value)) {
                return callback(new Error('密码输入有误，请检查格式是否正确！'));
            } else {
                callback()
                }
        }
        // 重新输入密码验证
        const repwdCheck = async(rule, value, callback) => {
            if(value !== this.formData.password) {
                return callback(new Error('两次密码输入不一致！'));
            } else {
                callback()
            }
        }
        return {
            active: 0,
            labelPosition: 'right', // 对齐方式
            Loading: true,          // 动画加载效果
            sendBtnTxt: '发送验证码', // 按钮显示内容
            msgBtnDisabled: false, // 按钮禁用状态
            timer: null, // 计时器
            countdown: 30, // 时间

            identifyCode: '', // 显示的验证码
            identifyCodeCheck: '', // 实际比较的验证码
            // returnCode:null,// 返回的验证码，用来比较
            returnCode:null,

            identifyCodes: '0123456789', // 验证码字符集合
            formData:{
                account:'',
                code:'',
                email:'',
                emailCode:'',
                password:'',
                rePassword:'',
 
            },
            rule:{
                account:[
                    {required: true,  message: '请输入账号' ,trigger: 'blur'},

                ],
                code:[
                        {required: true,  message: '请输入验证码' ,trigger: 'blur'},
                        { validator: validateCode, trigger: 'blur' }
                    ],
                email: [
                        { required: true,  message: '请输入用户绑定的手机' ,trigger: 'blur'},
                        { min: 11, max: 11, message: '长度为11位！', trigger: 'blur'},
                        {validator:phoneCheck, trigger: 'blur'},
                ],
                emailCode: [
                        { required: true,  message: '请输入手机验证码' ,trigger: 'blur'},
                        { validator: validatePhoneCode, trigger: 'blur' }
                        
                ],
                password:[
                        { required: true,  message: '新密码不能为空' ,trigger: 'blur'},
                        {validator:pwdCheck, trigger: 'blur'},
                        { min: 3, max: 8, message: '长度在3-8字符之间', trigger: 'blur'}
                ],
                rePassword:[
                        { required: true,  message: '重新密码不能为空' ,trigger: 'blur'},
                        {validator:repwdCheck, trigger: 'blur'},
                ],
            }

        }
    },
    methods: {
        changeActive(num){
            this.active = num
        },
        prev () {
            if (--this.active < 0) { this.active = 0 }
        },
        next () {
            // switch (this.active) {
            //     case 0:
            //         if (this.refindForm.code === '') { return this.$message.warning('验证码未填写！') }
            //         if (this.identifyCodeCheck !== this.refindForm.code && this.refindForm.code !== '') { return this.$message.warning('验证码错误！') }
            //         break
            //     case 1:
            //         var regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
            //         if (this.refindForm.email === '') return this.$message.warning('邮箱地址未填写！')
            //         if (this.refindForm.email !== '' && this.refindForm.emailCode === '') return this.$message.warning('邮箱验证码不能为空！')
            //         if (this.refindForm.emailCode !== '' && Number(this.refindForm.emailCode) !== Number(this.checkEmailCode)) return
            //         if (this.refindForm.email !== '' && !regEmail.test(this.refindForm.email)) return
            //         break
            // }

            this.$refs.form.validate((valid) => {
                if(valid){
                    // this.loading = true
                    // 模拟异步请求操作
                    setTimeout(() => {
                        // this.loading = false
                        if (this.active++ > 3) this.active = 0;
                    }, 200)
                }
            })
        },
        refind () {
            this.$refs.form.validate(async (valid) => {
                if(valid){
                    let form = {
                        username:this.formData.account,
                        password:this.$md5(this.formData.password)
                    }
                    const {data:res} =await this.$http.post('/user/forget',form)
                    console.log(res);
                    if(res.code!==200){
                        return this.$message.error("找回密码失败")
                    }
                    // this.loading = true
                    // 模拟异步请求操作
                    setTimeout(() => {
                        // this.loading = false
                        this.active += 1
                        this.LoadingTo()
                    }, 200)
                }
            })
            // 显示加载延迟效果
            
            // if (this.refindForm.password === '' || this.refindForm.rePassword === '') { return this.$message.warning('密码和确认密码不能为空！') }
            // if (this.refindForm.password !== '' && this.refindForm.rePassword !== '' && this.refindForm.password.length >= 6 && this.refindForm.rePassword === this.refindForm.password) {
            //   this.active += 1
            //   // http请求处理

            //   // 显示加载延迟效果
            //   this.LoadingTo()
            // }
            // this.$refs.refindFormRef.validate(async valid => {
            //     if (!valid) return
            //     // http请求处理
            //     const { data: res } = await this.$http.post('/user/findPassword', {
            //     email: this.refindForm.email,
            //     code: this.refindForm.emailCode,
            //     password: this.refindForm.password
            //     })
            //     // console.log(res)
            //     if (res.code !== 200) return this.$message.error('找回密码失败！')

            //     this.active += 1
            //     // 显示加载延迟效果
            //     this.LoadingTo()
            // })

        },
        // 延迟加载效果
        LoadingTo () {
            setTimeout(() => {
                this.Loading = !this.Loading
                this.active += 1
                this.$message.success('密码修改成功！')
            }, 2500)
        },
        // 返回登陆页面
        goback () {
            this.$router.push('/login')
        },
        // 发送验证码
        async sendCode () {
            let phoneNumber = this.formData.email
            if(this.formData.email){
                const {data:res} = await this.$http.post(`/user/update/code?phoneNumber=${phoneNumber}`,)
                console.log(res);
                if(res.code!==200){
                    return this.$message.error("发送验证码失败")
                }
                this.returnCode = res.data
                // console.log("abc");
            }
            else{
                return this.$message.error("请输入手机号")
                // console.log("bcd");
            }
            this.getCode()
        },
        // 发送验证码30秒倒计时
        getCode () {
            // console.log(this.sendCode())
            // // 发送验证码
            // if (this.sendCode() !== true) {
            //   return
            // }

            // 倒计时
            if (!this.timer) {
                this.timer = setInterval(() => {
                if (this.countdown > 0 && this.countdown <= 30) {
                    this.countdown--
                    if (this.countdown !== 0) {
                    this.sendBtnTxt = '重新发送(' + this.countdown + ')'
                    this.msgBtnDisabled = true
                    } else {
                    clearInterval(this.timer)
                    this.sendBtnTxt = '获取验证码'
                    this.countdown = 30
                    this.timer = null
                    this.msgBtnDisabled = false
                    }
                }
                }, 1000)
            }
        },
        // 刷新验证码
        refreshCode () {
            this.identifyCode = ''
            this.makeCode(this.identifyCodes, 4)
        },
        randomNum (min, max) {
            max = max + 1
            return Math.floor(Math.random() * (max - min) + min)
        },
        // 随机生成验证码字符串
            makeCode (data, len) {
            for (let i = 0; i < len; i++) {
                this.identifyCode += data[this.randomNum(0, data.length - 1)]
                this.identifyCodeCheck = this.identifyCode.toLowerCase()
            }
        }
    },
    created () {
        this.refreshCode()
    }
}
</script>

<style lang="less" scoped>
.retrieve-box{
    width: 100%;
    min-width: 1200px;
    height: calc(100% - 170px);
    min-height: 500px;
    background: url(../../assets/images/bg/login_bg.jpg) no-repeat 55% 0;
    position: relative;
}
.step-box{
    height: 450px;
    width: 1000px;
    border-radius: 6px;
    background: rgba(255, 255, 255, 1);
    padding: 25px 25px 5px 25px;
    position: absolute;

    top: 45%;
    left: 50%;
    transform: translate(-50%, -50%);
    .steps{
        .el-steps--simple{
            background-color: #fff;
        }
        margin-bottom: 20px;
        /deep/.el-step__line{
            background: transparent;
            border-top: 5px dotted;
            top: 50% !important;
            color:#ddd;
            .el-step__line-inner{
            border-width: 0 !important;
            }
        }
        /deep/.el-step__icon.is-icon{
            height: 50px;
            width: 50px;
            border-radius: 50%;
            border: 3px solid #409EFF;
            cursor: pointer;
            color: #ccc;
        }
        /deep/.is-finish{
            .el-step__icon.is-icon{
                height: 50px;
                width: 50px;
                border-radius: 50%;
                border: 2px solid #409EFF;
                cursor: pointer;
                background-color: #409EFF;
                color: #fff;
            }
            /deep/.el-step__line{
                color:#409EFF;
            }
        }
        .el-step__title.is-finish{
            font-weight: 700 !important;
        }
        .el-step__title.is-process{
            color: #aaa !important;
        }
    }
}
.contents{
    height: 300px;
    display: flex;
    justify-content: center;
    // align-items: center;
    padding-top: 25px;
    .el-form{
        width: 50%;
        padding: 10px 5px;
        
        .retrieve-code {
            float: right;
            cursor: pointer;
        }
        .email_tip{
            position: relative;
            left: 20%;
            bottom: 20px;
            font-size: 18px;
            color: #a5a5a5;
        }
        .deployBtn{
            margin-top:25px;
            position:absolute;
            display: flex;
            justify-content: center;
            bottom:30px;
            left: 50%;
            transform: translate(-50%, -50%);
            .btn_next{
                width: 250px;
            }
        }
        .send{
            float:right;
        }
        .load{
            height: 4em;
            font-size: 2.2em;
        }
        .tip_success{
            text-align: center;
            .icon_success{
                font-size: 8em;
                color: rgb(68, 196, 36);
            }
            p{
                margin-top:20px;
                font-size:1.0em;
                color: #999;
            }
        }
    }
}

</style>